using Devil;
using LitJson;
using UnityEditor.AssetImporters;
using UnityEngine;

namespace GameToolkit.Editor
{
    public abstract class JsonAssetImpoter<T> : ScriptedImporter where T : ScriptableObject
    {

        public override void OnImportAsset(AssetImportContext ctx)
        {
            try
            {
                JsonSerializedObject.InitWrappers();
                var path = ctx.assetPath;
                if (path.StartsWithIgnoreCase("Packages/"))
                {
                    var pack = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(path);
                    if (pack != null)
                    {
                        var file = path.Substring(pack.assetPath.Length + 1);
                        path = NativeFileSystem.Combine(pack.resolvedPath, file);
                    }
                }
                var txt = NativeFileSystem.ReadAllText(path);
                var json = JsonMapper.ToObject(txt);
                var asset = JsonSerializedObject.ImportFromJson<T>(json);
                asset.name = NativeFileSystem.GetFileName(ctx.assetPath, true);
                ctx.AddObjectToAsset("Main", asset);
                ctx.SetMainObject(asset);
            }
            catch (System.Exception e)
            {
                Debug.LogError($"Failed to import asset @{ctx.assetPath}\n{e}");
            }
        }
    }
}
